package cn.kgc.javaweb.servlet;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.kgc.javaweb.entity.Student;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

/**
 * excel的导出
 * @author: mosin
 * @version: v1.0  2022/3/23
 */
@WebServlet("/export")
public class ExportServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // TODO  查询数据库   返回需要导出的数据
        ArrayList<Student> students = new ArrayList<>();
        Student student = Student.builder().age(20).birth(new Date()).email("985732654@qq.com").name("tom").sex("男").build();
        students.add(student);
        students.add(student);
        students.add(student);
        students.add(student);
        students.add(student);
        students.add(student);

        //将数据导出到表格    1.表格的配置参数(表格的标题，sheet的名字)  2.导出的数据类型   .class  3.导出的数据集合
        ExportParams exportParams = new ExportParams("学生信息表", "java2114班学生信息");
        //返回一个工作簿  就是一个excel文件
        Workbook sheets = ExcelExportUtil.exportExcel(exportParams, Student.class, students);
        //生成工作簿导出的位置
        FileOutputStream fos = new FileOutputStream("D:\\upload\\students.xls");
        //将工作部写出
        sheets.write(fos);
        //释放资源
        fos.close();
        sheets.close();
    }
}
